<template>
  <div class="root-container" v-loading.fullscreen.lock="isLoading">
    <!-- <h1>CEM空域组合</h1> -->
    <!-- <el-card shadow="never"> -->
    <!-- <template #header> -->
    <div class="card-header-container">
      <span class="card-title">
        <span>CEM</span>
        <el-icon><ArrowRightBold /></el-icon>
        <span>空域组合设置</span>
      </span>
      <span>
        <el-button type="primary" link :disabled="!isValid" @click="handleSave">
          <el-icon><UploadFilled /></el-icon>
          <span>保存</span>
        </el-button>
        <el-button type="warning" link @click="handleReset">
          <el-icon><RefreshLeft /></el-icon>
          <span>清空</span>
        </el-button>
        <el-button
          type="danger"
          link
          :disabled="!isExisted"
          @click="handleDelete"
        >
          <el-icon><DeleteFilled /></el-icon>
          <span>删除</span>
        </el-button>
      </span>
    </div>
    <!-- </template> -->
    <div class="card-content-container">
      <el-row :gutter="20">
        <el-col :xs="24" :sm="12" :md="8" :lg="5">
          <el-scrollbar :height="contentHeight">
            <div class="card-subitem-container border-right">
              <el-text
                v-if="CEMStore.areas.length == 0"
                type="info"
                size="small"
              >
                <el-icon><InfoFilled /></el-icon>
                <span style="padding-left: 6px">未找到已保存的空域组合</span>
              </el-text>
              <!-- <el-button
                v-for="item in CEMStore.areas"
                class="area-item-button"
                type="primary"
                size="small"
                :text="identifier != item.identifier"
                @click="handleSelect(item)"
              >
                <span>{{ item.identifier }}</span>
              </el-button> -->
              <div
                v-for="item in CEMStore.areas"
                :class="[
                  'area-item-option',
                  identifier == item.identifier
                    ? 'area-item-option-selected'
                    : 'area-item-option-unselected',
                ]"
                @click="handleSelect(item)"
              >
                <span>{{ item.identifier }}</span>
              </div>
            </div>
          </el-scrollbar>
        </el-col>
        <el-col :xs="24" :sm="12" :md="16" :lg="19">
          <el-scrollbar :height="contentHeight">
            <div class="card-subitem-container page-container">
              <el-form label-width="90" size="small">
                <el-form-item label="组合标识符">
                  <span v-if="isValid">
                    <el-text type="primary">
                      <el-icon><CircleCheckFilled /></el-icon>
                      <span>&nbsp;{{ identifier }}</span>
                    </el-text>
                    <el-tag
                      v-if="isExisted"
                      type="info"
                      style="margin-left: 12px"
                    >
                      已有
                    </el-tag>
                    <el-tag v-else type="info" style="margin-left: 12px">
                      新增
                    </el-tag>
                  </span>
                  <span v-else>
                    <el-text type="danger">
                      <el-icon><CircleCloseFilled /></el-icon>
                      <span>&nbsp;Emm...&emsp;&emsp;/ᐠ｡ꞈ｡ᐟ\</span>
                    </el-text>
                    <el-tag type="danger" style="margin-left: 12px">
                      错误
                    </el-tag>
                  </span>
                </el-form-item>
                <el-form-item :label="`适用模式 (${formData.modes.length})`">
                  <el-checkbox-group v-model="formData.modes">
                    <el-checkbox v-for="item in params.modes" :label="item" />
                  </el-checkbox-group>
                </el-form-item>
                <el-form-item :label="`包含空域 (${formData.models.length})`">
                  <el-checkbox-group v-model="formData.models">
                    <el-checkbox v-for="item in params.models" :label="item" />
                  </el-checkbox-group>
                </el-form-item>
                <el-form-item label="负荷限制">
                  <span class="limits-item-container">
                    <el-text>15分钟基线</el-text>
                    <el-input-number
                      ref="QuarterlyBaseline"
                      @mouseenter="$refs.QuarterlyBaseline.focus()"
                      @focus="(event) => event.currentTarget.select()"
                      @mousewheel.prevent
                      controls-position="right"
                      v-model="formData.limits.baselineQuarter"
                      size="small"
                      :step="1"
                      :min="0"
                      :max="9999"
                      class="limits-item-value"
                    />
                  </span>
                  <span class="limits-item-container">
                    <el-text>60分钟基线</el-text>
                    <el-input-number
                      ref="HourlyBaseline"
                      @mouseenter="$refs.HourlyBaseline.focus()"
                      @focus="(event) => event.currentTarget.select()"
                      @mousewheel.prevent
                      controls-position="right"
                      v-model="formData.limits.baselineHour"
                      size="small"
                      :step="1"
                      :min="0"
                      :max="9999"
                      class="limits-item-value"
                    />
                  </span>
                  <span class="limits-item-container">
                    <el-text>15分钟上限</el-text>
                    <el-input-number
                      ref="QuarterlyMaximum"
                      @mouseenter="$refs.QuarterlyMaximum.focus()"
                      @focus="(event) => event.currentTarget.select()"
                      @mousewheel.prevent
                      controls-position="right"
                      v-model="formData.limits.maximumQuarter"
                      size="small"
                      :step="1"
                      :min="0"
                      :max="9999"
                      class="limits-item-value"
                    />
                  </span>
                  <span class="limits-item-container">
                    <el-text>60分钟上限</el-text>
                    <el-input-number
                      ref="HourlyMaximum"
                      @mouseenter="$refs.HourlyMaximum.focus()"
                      @focus="(event) => event.currentTarget.select()"
                      @mousewheel.prevent
                      controls-position="right"
                      v-model="formData.limits.maximumHour"
                      size="small"
                      :step="1"
                      :min="0"
                      :max="9999"
                      class="limits-item-value"
                    />
                  </span>
                </el-form-item>
                <el-form-item>
                  <template #label>
                    <div style="width: 100%; text-align: right">
                      <div>基础标签设置</div>
                      <div>
                        <el-text type="info">
                          <el-icon><CaretLeft /></el-icon>
                          <span>负荷系数</span>
                        </el-text>
                      </div>
                      <div>
                        <el-text type="info">
                          <span>进入时延</span>
                          <el-icon><CaretRight /></el-icon>
                        </el-text>
                      </div>
                      <div>
                        <el-text :type="ratioSummary > 0 ? 'info' : 'danger'">
                          合计：{{ ratioSummary }}
                        </el-text>
                      </div>
                    </div>
                  </template>
                  <!-- @mousewheel.prevent -->
                  <span
                    class="tag-item-container"
                    v-for="(cell, index) in formData.content"
                  >
                    <el-text class="tag-item-label" :type="labelType(cell.tag)">
                      {{ cell.tag }}
                    </el-text>
                    <!-- ratio input -->
                    <el-input-number
                      :ref="cell.tag + '_RATIO'"
                      @mouseenter="
                        () => {
                          // $refs[cell.tag + '_RATIO'][0]
                          //   ? $refs[cell.tag + '_RATIO'][0].focus()
                          //   : null;
                        }
                      "
                      @focus="(event) => event.currentTarget.select()"
                      v-model="formData.content[index].ratio"
                      controls-position="right"
                      size="small"
                      :precision="2"
                      :step="1"
                      :min="0"
                      :max="99"
                      class="tag-item-ratio"
                    />
                    <!-- delay input -->
                    <el-input-number
                      :ref="cell.tag + '_DELAY'"
                      @mouseenter="
                        () => {
                          // $refs[cell.tag + '_DELAY']
                          //   ? $refs[cell.tag + '_DELAY'][0].focus()
                          //   : null;
                        }
                      "
                      @focus="(event) => event.currentTarget.select()"
                      v-model="formData.content[index].delay"
                      controls-position="right"
                      size="small"
                      :step="1"
                      :min="0"
                      :max="30"
                      class="tag-item-delay"
                    />
                  </span>
                  <!-- <el-text :type="ratioSummary > 0 ? 'info' : 'danger'">
              Rratio summary:&nbsp;{{ ratioSummary }}
            </el-text> -->
                </el-form-item>
                <el-form-item>
                  <template #label>
                    <div style="width: 100%; text-align: right">
                      <div>附加标签设置</div>
                      <div>
                        <el-text type="info">
                          <el-icon><CaretLeft /></el-icon>
                          <span>负荷系数</span>
                        </el-text>
                      </div>
                      <div>
                        <el-text type="info">
                          <span>进入时延</span>
                          <el-icon><CaretRight /></el-icon>
                        </el-text>
                      </div>
                      <div>
                        <el-text
                          :type="extraRatioSummary > 0 ? 'info' : 'danger'"
                        >
                          合计：{{ extraRatioSummary }}
                        </el-text>
                      </div>
                    </div>
                  </template>
                  <span
                    class="tag-item-container"
                    v-for="(cell, index) in formData.extraContent"
                  >
                    <el-text class="tag-item-label" :type="labelType(cell.tag)">
                      {{ cell.tag }}
                    </el-text>
                    <!-- ratio input -->
                    <el-input-number
                      :ref="cell.tag + '_RATIO'"
                      @mouseenter="
                        () => {
                          // $refs[cell.tag + '_RATIO'][0]
                          //   ? $refs[cell.tag + '_RATIO'][0].focus()
                          //   : null;
                        }
                      "
                      @focus="(event) => event.currentTarget.select()"
                      v-model="formData.extraContent[index].ratio"
                      controls-position="right"
                      size="small"
                      :precision="2"
                      :step="1"
                      :min="0"
                      :max="99"
                      class="tag-item-ratio"
                    />
                    <!-- delay input -->
                    <el-input-number
                      :ref="cell.tag + '_DELAY'"
                      @mouseenter="
                        () => {
                          // $refs[cell.tag + '_DELAY']
                          //   ? $refs[cell.tag + '_DELAY'][0].focus()
                          //   : null;
                        }
                      "
                      @focus="(event) => event.currentTarget.select()"
                      v-model="formData.extraContent[index].delay"
                      controls-position="right"
                      size="small"
                      :step="1"
                      :min="0"
                      :max="30"
                      class="tag-item-delay"
                    />
                  </span>
                  <!-- <el-text :type="extraRatioSummary > 0 ? 'info' : 'danger'">
              Rratio summary:&nbsp;{{ extraRatioSummary }}
            </el-text> -->
                </el-form-item>
              </el-form>
            </div>
          </el-scrollbar>
        </el-col>
      </el-row>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted, onUnmounted } from "vue";
import { ElMessage, ElMessageBox, ElNotification } from "element-plus";
import axios from "axios";
import dayjs from "dayjs";
import useFlowStore from "@/store/flow.js";
import useCommonStore from "@/store/common.js";
import useCEMStore from "@/store/CEM.js";

import params from "../common/params.json";

const flowStore = useFlowStore();
const commonStore = useCommonStore();
const CEMStore = useCEMStore();

const formData = ref({
  identifier: "",
  modes: [],
  models: [],
  limits: {
    baselineQuarter: 720,
    baselineHour: 2160,
    maximumQuarter: 720,
    maximumHour: 2160,
  },
  content: [],
});

const identifier = computed(() =>
  formData.value.modes.length > 0 && formData.value.models.length > 0
    ? formData.value.modes.sort().join(", ") +
      " / " +
      formData.value.models.sort().join(", ")
    : ""
);

const ratioSummary = computed(() => {
  if (!formData.value.content) return 0;
  let value = 0;
  formData.value.content.forEach((cell) => {
    value += cell.ratio;
  });
  return value;
});

const extraRatioSummary = computed(() => {
  if (!formData.value.extraContent) return 0;
  let value = 0;
  formData.value.extraContent.forEach((cell) => {
    value += cell.ratio;
  });
  return value;
});

const isValid = computed(
  () => identifier.value.length > 0 && ratioSummary.value > 0
);

const isExisted = computed(
  () =>
    CEMStore.areas.filter((area) => area.identifier == identifier.value)
      .length > 0
);

const labelType = (tag) =>
  tag.includes("DEP") || tag.includes("_D_")
    ? "success"
    : tag.includes("ARR") || tag.includes("_A_")
    ? "warning"
    : "info";

// const tags = computed(() => flowStore.tags);

const handleSelect = (data) => {
  let d = JSON.parse(JSON.stringify(data));
  formData.value.identifier = d.identifier;
  formData.value.modes = d.modes;
  formData.value.models = d.models;
  formData.value.limits = d.limits;
  formData.value.content = d.content;
};

const handleDelete = async () => {
  isLoading.value = true;
  await CEMStore.deleteArea(formData.value);
  isLoading.value = false;
};

const isLoading = ref(false);

const handleSave = async () => {
  isLoading.value = true;
  formData.value.identifier = identifier.value;
  await CEMStore.saveArea(formData.value);
  isLoading.value = false;
};

const handleReset = (alert = true) => {
  // initialize form data
  formData.value = {
    identifier: "",
    modes: [],
    models: [],
    limits: {
      baselineQuarter: 720,
      baselineHour: 2160,
      maximumQuarter: 720,
      maximumHour: 2160,
    },
    content: [],
    extraContent: [],
  };

  // generate content
  params.tags.forEach((tag) => {
    formData.value.content.push({
      tag: tag,
      ratio: 0,
      delay: 0,
    });
  });

  // generate extra content
  params.extraTags.forEach((tag) => {
    formData.value.extraContent.push({
      tag: tag,
      ratio: 0,
      delay: 0,
    });
  });

  if (alert) {
    ElMessage({
      type: "info",
      message: "已重置表表单内容",
    });
  }
};

const stopScroll = (evt) => {
  // evt.preventDefault();
  // evt.stopPropagation();
  // evt.cancelBubble = true;
  // evt.returnValue = false;
  // return false;
};

const contentHeight = computed(() => commonStore.clientHeight - 199 + "px");

onMounted(() => {
  handleReset(false);
});
</script>

<style scoped>
@import "../common/card.css";
</style>
